package com.gshocklab.bulkposter.connection;

import java.util.ArrayList;
import java.util.List;

import oauth.signpost.OAuthProvider;
import oauth.signpost.commonshttp.CommonsHttpOAuthConsumer;
import oauth.signpost.commonshttp.CommonsHttpOAuthProvider;

import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.BasicResponseHandler;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreProtocolPNames;
import org.apache.http.protocol.HTTP;
import org.json.JSONObject;

import android.util.Log;

import com.gshocklab.bulkposter.data.AccountType;
import com.gshocklab.bulkposter.data.AccountTypesProvider;
import com.gshocklab.bulkposter.data.dto.SocialAccount;

/**
 * Utils for working with network
 * @author vitaliy gashock
 */

public final class TwitterConnectionHelper {
	// Twitter constants
	public static final String TWITTER_CONSUMER_KEY = "1zHA0FYdrL53rhXMjEiJw";
	public static final String TWITTER_CONSUMER_SECRET = "DG2zVaYCz3qGSki4safP8CBo17LEfMNi1Eg01iLTL4";
	public static final String TWITTER_REQUEST_TOKEN_URL = "http://twitter.com/oauth/request_token";
	public static final String TWITTER_ACCESS_TOKEN_URL = "http://twitter.com/oauth/access_token";
	public static final String TWITTER_AUTHORIZE_URL = "http://twitter.com/oauth/authorize";
	public static final String TWITTER_CALLBACK_URL = "bulkposter://twitt";
	
	// API URLs
	private static final String TWITTER_API_URL = "http://api.twitter.com/1/";
	private static final String VERIFY_CREDS_URL = TWITTER_API_URL + "account/verify_credentials.json";
	private static final String UPDATE_STATUS_URL = TWITTER_API_URL + "statuses/update.json";
	
	private static CommonsHttpOAuthConsumer oauthConsumer = new CommonsHttpOAuthConsumer(TWITTER_CONSUMER_KEY, TWITTER_CONSUMER_SECRET);
	private static OAuthProvider oauthProvider = new CommonsHttpOAuthProvider(TWITTER_REQUEST_TOKEN_URL, TWITTER_ACCESS_TOKEN_URL, TWITTER_AUTHORIZE_URL);
	
	private static final HttpClient client = new DefaultHttpClient();
	
	/**
	 * Request new twitter account token URL
	 * @return
	 */
	public static String requestTwitterTokenUrl() {
		try {
			return oauthProvider.retrieveRequestToken(oauthConsumer, TWITTER_CALLBACK_URL);
		} catch (Exception e) {
			return null;
		}
	}
	
	/**
	 * Register and verify twitter account
	 * @param verifierUrl
	 * @return
	 */
	public static SocialAccount registerNewTwitterAccount(String verifierUrl) {
		try {
			oauthProvider.retrieveAccessToken(oauthConsumer, verifierUrl);
			
			HttpGet getRequest = new HttpGet(VERIFY_CREDS_URL);
			oauthConsumer.sign(getRequest);
			
			ResponseHandler<String> responseHandler = new BasicResponseHandler();
			String responseBody = client.execute(getRequest, responseHandler);
			
			if (responseBody != null) {
				final JSONObject json = new JSONObject(responseBody);
				final SocialAccount account = new SocialAccount();
				
				if (json.has("screen_name")) {
					account.username = json.getString("screen_name");
				}
				
				if (json.has("profile_image_url")) {
					account.avatarUrl = json.getString("profile_image_url");
				}
				
				account.type = AccountTypesProvider.accountTypes.get(AccountType.TWITTER_ACCOUNT);
				
				account.accountToken = oauthConsumer.getToken();
				account.secretAccountToken = oauthConsumer.getTokenSecret();
				account.password = "password";
				
				return account;
			}
			return null;
		} catch (Exception e) {
			Log.e("NCH", e.getMessage());		
			return null;
		}
	}
	
	public static boolean sendStatusUpdate(final SocialAccount account, String statusMessage) {
		final List<NameValuePair> params = new ArrayList<NameValuePair>();
		params.add(new BasicNameValuePair("status", statusMessage));
		
		HttpPost postRequest = new HttpPost(UPDATE_STATUS_URL);

		try {
			postRequest.setEntity(new UrlEncodedFormEntity(params, HTTP.UTF_8));
			postRequest.getParams().setBooleanParameter(CoreProtocolPNames.USE_EXPECT_CONTINUE, false);
			
			oauthConsumer.setTokenWithSecret(account.accountToken, account.secretAccountToken);
			oauthConsumer.sign(postRequest);
			
			HttpResponse response = client.execute(postRequest);
			
			return response.getStatusLine().getStatusCode() == 200;
		} catch (Exception e) {
			return false;
		}
	}
}
